package com.me.study.concurrent.threadPool;

import com.me.common.util.SleepUtil;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务线程池：shutdown、shutdownNow
 *
 * @author ME
 * @date 2021/2/8
 */
public class TestScheduledExecutorService {

    public static void main(String[] args) {
        // 延迟执行：无返回     schedule()
        startScheduleRunnable();

        // 延迟执行：有返回     schedule()
        startScheduleCallable();
        // 周期执行：固定速率，慢了会追赶，但不会同时执行多个        scheduleAtFixedRate()
        startScheduleAtFixedRate();
        // 周期执行：固定间隔，上一次执行完后间隔指定时间再执行       scheduleWithFixedDelay()
        startScheduleWithFixedDelay();

    }

    /**
     * 延迟执行任务 schedule：指定间隔后执行一次，不带返回值
     */
    public static void startScheduleRunnable() {
        ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
        schedule.schedule(() -> {
            System.out.println("Sleep 3 s...");
            SleepUtil.seconds(3);
            System.out.println("end...");

            // while (true) {
            // }
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 延迟执行任务 schedule：指定间隔后执行一次，带返回值
     */
    public static void startScheduleCallable() {
        ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
        schedule.schedule(() -> {
            System.out.println("Sleep 3 s...");
            SleepUtil.seconds(3);
            System.out.println("end...");
            return "";
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 周期性执行任务 scheduleAtFixedRate：固定速率，慢了会追赶，但不会同时执行多个
     */
    public static void startScheduleAtFixedRate() {
        ThreadFactory lang3Factory = new BasicThreadFactory.Builder().namingPattern("lang3Thread-pool-thread-%d").build();
        ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor(lang3Factory);

        schedule.scheduleAtFixedRate(() -> {
            System.out.println("Sleep 3 s...");
            SleepUtil.seconds(3);
            System.out.println("end...");
        }, 5, 3, TimeUnit.SECONDS);

        // TODO schedule.shutdown() 会 终止 未执行的任务，某一次周期性执行后，相当于变成了未执行
        schedule.shutdown();
    }

    /**
     * 周期性执行任务 scheduleWithFixedDelay：固定间隔，上一次执行完后间隔指定时间再执行
     */
    public static void startScheduleWithFixedDelay() {
        ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
        schedule.scheduleWithFixedDelay(() -> {
            System.out.println("Sleep 3 s...");
            SleepUtil.seconds(3);
            System.out.println("end...");
        }, 5, 3, TimeUnit.SECONDS);
    }

}
